
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.StringTokenizer;

import javax.servlet.http.*;  // provides servlet functionality
import javax.servlet.*;	      // ditto
import javax.*;


public class Signup extends HttpServlet {
	
	private final static String REDIRECT_TO_LOGIN_CODE 
	= "<meta http-equiv=\"REFRESH\" content=\"3;url=../Login.jsp\">";
	
	private final static String REDIRECT_TO_CART_CODE 
	= "<meta http-equiv=\"REFRESH\" content=\"3;url=ShoppingCart\">";
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws IOException, ServletException
	{
		if (!Bridge.hasBeenToMainPage(request.getSession(), response.getWriter()))
		{
			return;
		}
		
		System.out.println("\n---Doing Post in Signup---\n");
		
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		
		String firstName = request.getParameter("signup_firstname");
		String lastName = request.getParameter("signup_lastname");
		String email = request.getParameter("signup_email");
		String password = request.getParameter("signup_password");
		String verifyPassword = request.getParameter("signup_verifypassword");
		
		if (firstName == null || firstName.equals("") || lastName == null || lastName.equals("") || 
			email == null || email.equals("") || password == null || password.equals("") || 
			verifyPassword == null || verifyPassword.equals("") )
		{
			out.print("<html><head><title>Redirecting...</title>"
					+ REDIRECT_TO_LOGIN_CODE + "</head>"
					+ "<body><font color=\"red\">There's a problem with your information.<br>" +
							"All fields are required. Please try again.</font></body>" 
					+"</html>");
			return;
		}
		else if (!password.equals(verifyPassword))
		{
			out.print("<html><head><title>Redirecting...</title>"
					+ REDIRECT_TO_LOGIN_CODE + "</head>"
					+ "<body><font color=\"red\">The passwords you entered didn't match.<br>" +
							"Please try again.</font></body>" 
					+"</html>");
			return;
		}
		
		try
		{
			Class.forName("org.postgresql.Driver").newInstance();
			Connection connection = DriverManager.getConnection(
					"jdbc:postgresql://localhost/fabflixs", "testuser", "testpass");
		
			Statement select = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
	                ResultSet.CONCUR_UPDATABLE);
			Statement select2 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
	                ResultSet.CONCUR_UPDATABLE);
			ResultSet resultPasswordMatch = select.executeQuery("Select * from customers WHERE email=\'" 
					+ email + "\' AND password=\'" + password + "\'");
			ResultSet resultEmailMatch = select2.executeQuery("Select * from customers WHERE email=\'" 
					+ email + "\'");
			
			boolean passwordMatch = resultPasswordMatch.last();
			boolean emailMatch = resultEmailMatch.last();
			
			if (passwordMatch)
			{
				out.print("<html><head><title>Redirecting...</title>"
						+ REDIRECT_TO_CART_CODE + "</head>"
						+ "<body>You already have an account. Logging you in...</font></body>" 
						+"</html>");
				
				Bridge.logUserIn(email, session);
				//session.setAttribute(Constants.loggedInUserAttributeName, email);
				
				return;
			}
			else if (emailMatch)
			{
				out.print("<html><head><title>Redirecting...</title>"
						+ REDIRECT_TO_LOGIN_CODE + "</head>"
						+ "<body>You already have an account. Please log in.</font></body>" 
						+"</html>");
				return;
			}
			else //register this user
			{
				Statement select3 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
		                ResultSet.CONCUR_UPDATABLE);
				ResultSet resultCustomers = select3.executeQuery("Select * from customers");
				Statement select4 = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
				ResultSet resultCustomerMaxId = select4.executeQuery("Select max(id) from customers");				
				
				resultCustomerMaxId.next();
				int newCustomerId = resultCustomerMaxId.getInt(1) + 1;
				
				resultCustomers.moveToInsertRow();
				resultCustomers.updateInt("id", newCustomerId);
				resultCustomers.updateString("first_name", firstName);
				resultCustomers.updateString("last_name", lastName);
				resultCustomers.updateString("email", email);
				resultCustomers.updateString("password", password);
				
				resultCustomers.insertRow();
				
				out.print("<html><head><title>Redirecting...</title>"
						+ REDIRECT_TO_CART_CODE + "</head>"
						+ "<body>Your account has been created. Logging you in...</font></body>" 
						+"</html>");
				
				session.setAttribute(Constants.loggedInUserAttributeName, email);				
				
				return;
			}
		}
		catch (Exception e)
		{
			out.println("Exception: " + e.getMessage());
			e.printStackTrace();
		}
	}
	
}
